﻿using System;
using System.Configuration;
using System.Web.Configuration;

namespace NCMIS.Provider
{
    /// <summary>
    /// Represents the single instance of the Provider Manager that initializes the default provider and the provider collection.
    /// </summary>
    public static class MultiFilingProviderManager
    {
        private static MultiFilingProviderBase defaultProvider;
        private static MultiFilingProviderCollection providers;

        /// <summary>
        /// Creates an instance of the <see cref="NCMIS.Provider.MultiFilingProviderManager"/> class.
        /// </summary>
        static MultiFilingProviderManager()
        {
            Initialize();
        }

        /// <summary>
        /// Initializes the the <see cref="NCMIS.Provider.MultiFilingProviderManager"/> class.
        /// </summary>
        private static void Initialize()
        {
            MultiFilingProviderConfiguration configuration = (MultiFilingProviderConfiguration)ConfigurationManager.GetSection("MultiFilingProvider");

            if (configuration == null)
            {
                throw new ConfigurationErrorsException("MultifilingProvider configuration section is not set correctly.");
            }

            providers = new MultiFilingProviderCollection();

            try
            {
                ProvidersHelper.InstantiateProviders(configuration.Providers, providers, typeof(MultiFilingProviderBase));
            }
            catch (Exception)
            {
                throw new ConfigurationErrorsException("MultifilingProvider configuration section is not set correctly.");
            }

            providers.SetReadOnly();
            defaultProvider = providers[configuration.Default];

            if (defaultProvider == null)
                throw new Exception("defaultProvider");
        }

        /// <summary>
        /// Gets the current provider.
        /// </summary>
        public static MultiFilingProviderBase Provider
        {
            get { return defaultProvider; }
        }

        /// <summary>
        /// Gets the current provider collection.
        /// </summary>
        public static MultiFilingProviderCollection Providers
        {
            get { return providers; }
        }
    }
}